package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/call")
public class RollCallServlet extends HttpServlet {
    private static int count;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        switch (req.getParameter("method")) {
            case "show":
                show(req, resp);
                break;
            case "count":
                count(req, resp);
                break;
        }
    }

    private void count(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.getWriter().print(count);
    }

    private void show(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        InputStream is = this.getClass().getResourceAsStream("/names.txt");
        InputStreamReader isr = new InputStreamReader(is, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String str;
        List<String> list = new ArrayList<>();
        while ((str = br.readLine()) != null) {
            if (str.trim() != "") {
                list.add(str);
            }
        }
        count = list.size();
        br.close();
        ObjectMapper mapper = new ObjectMapper();
        resp.getWriter().print(mapper.writeValueAsString(list));
    }
}
